package controllers

import (
	"auusoft/AuuWiki/Models"
	"strings"
	"time"
)

type EditController struct {
	RootController
}

func (this *EditController) Get() {
	this.Data["username"] = this.CheckSession()

	this.Ctx.Request.ParseForm()
	title := this.Ctx.Request.Form.Get("wiki")
	wikis, _ := models.GetWikiByTitle(title)
	content := ""
	if len(wikis) <= 0 {
		content = title + "\r\n"
	} else {
		content = strings.Replace(wikis[0].Content, "[br]", "\r\n", -1)
		content = title + "\r\n" + content
	}
	if title == "" {
		this.Data["title2"] = "新的Wiki"
	} else {
		this.Data["title2"] = title
	}

	this.Data["ccc"] = content
	this.Layout = "layout.html"
	this.TplNames = "Edit.html"
}

func (this *EditController) Post() {
	username := this.CheckSession()
	ti := time.Now().String()

	this.Ctx.Request.ParseForm()
	content := this.Ctx.Request.Form.Get("content")

	title := GetTitle(content)

	cc := GetContent(content)

	if title == "" {
		this.Data["username"] = username
		this.Data["title2"] = "新的Wiki"
		this.Layout = "layout.html"
		this.TplNames = "Edit.html"
		return
	}

	wikis, _ := models.GetWikiByTitle(title)

	if len(wikis) <= 0 {
		wiki := models.Wiki{}
		wiki.Title = title
		wiki.Content = cc
		wiki.Log = username.(string) + ` 创建于: ` + ti

		models.InsertWiki(wiki)
	} else {
		wikis[0].Content = cc
		wikis[0].Log = wikis[0].Log + "<br/>" + username.(string) + " 修改于: " + ti

		models.UpdateWiki(wikis[0])
	}

	this.Ctx.Redirect(302, "/?wiki="+title)
}
